<template>
  <div class="chat-frame-container">
    <div class="chat-info-area">
      <div class="user-info">
        <v-avatar size="64">
          <img
              :src="userInfo.avatar"
              alt="John">
        </v-avatar>
        <div class="name-and-status">
          <div class="username">
            {{ userInfo.friendBeiZu === ""||userInfo.friendBeiZu === null ? userInfo.nickname : userInfo.friendBeiZu }}
          </div>
          <div class="status">
            <v-badge
                inline dot left
                color="green">
              当前在线
            </v-badge>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <v-btn icon color="#999">
          <v-icon size="18">fas fa-video</v-icon>
        </v-btn>
        <v-btn icon color="#999">
          <v-icon size="18">fas fa-phone</v-icon>
        </v-btn>
        <v-menu
            rounded="lg"
            offset-y
            left
            transition="slide-y-transition"
            bottom>
          <template v-slot:activator="{ attrs, on }">
            <v-btn
                icon
                color="#999"
                v-bind="attrs"
                v-on="on">
              <v-icon size="18">fas fa-ellipsis-v</v-icon>
            </v-btn>
          </template>
          <v-list>
            <v-list-item
                v-for="userMenuItem in userMenu"
                :key="userMenuItem"
                link>
              <v-list-item-title v-text="userMenuItem"></v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </div>
    </div>
    <div class="message-area" ref="messageArea">
      <div
          class="message-container"
          v-for="(message, index) in messageRecords"
          :key="message.id"
          :id="`message${message.id}`">
        <!-- 消息发送时间容器 -->
        <div
            class="datetime-container"
            v-if="computeDatetime(messageRecords[index - 1] === undefined ? 0 : messageRecords[index - 1].time, message.time)">
          {{ message.time | formatTime }}
        </div>
        <!-- 用户头像容器 -->
        <div
            class="avatar-container"
            :class="message.senderId !== myInfo.id ? 'avatar-container-left' : 'avatar-container-right'">
          <v-avatar v-if="message.senderId !== myInfo.id ">
            <v-img :src="userInfo.avatar"></v-img>
          </v-avatar>
          <v-avatar v-if="message.senderId === myInfo.id">
            <v-img :src="myInfo.avatar"></v-img>
          </v-avatar>
        </div>
        <!-- 消息内容 -->
        <div
            v-ripple
            class="message-content"
            :data-name="`message${index}`"
            :class="message.senderId !== myInfo.id ? 'message-content-left' : 'message-content-right'">
          <div v-if="message.messageType === 'text'">
            {{ message.message }}
          </div>
          <v-img
              max-height="150"
              max-width="250"
              contain
              v-if="message.messageType === 'image'"
              :src="message.message"
              :data-name="`message${index}`"/>
          <div v-if="message.messageType === 'file'" @click="downloadFile(message.message)">
            {{ message.message.substring(message.message.lastIndexOf("/")+1) }}
          </div>
        </div>
      </div>
    </div>
    <div class="edit-message-area">
      <div class="btn-area">
        <v-file-input
            @change="handleFileSelected"
            prepend-icon="fas fa-paperclip"
            hide-input hide-details
            placeholder="请选择发送的文件">
        </v-file-input>
        <v-file-input
            accept="image/png, image/jpeg"
            @change="handleImageSelected"
            prepend-icon="fas fa-image"
            hide-input hide-details
            placeholder="请选择发送的图片">
        </v-file-input>
        <v-btn icon color="#999" small>
          <v-icon size="18">fas fa-laugh</v-icon>
        </v-btn>
      </div>
      <div class="input-area">
        <v-textarea
            label="分享生活的喜悦 ..."
            auto-grow solo flat hide-details
            v-model="textAreaValue"
            color="#333"
            background-color="transparent"
            rows="2"/>
      </div>
      <div class="send-btn-area">
        <v-btn
            fab depressed
            :color="customerColor"
            width="50"
            height="50"
            @click="handleSendBtnClick">
          <v-icon
              color="#fff"
              size="20">
            fas fa-paper-plane
          </v-icon>
        </v-btn>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {getSingleChatHistory} from "../../../api";

export default {
  name: "chatFrame",
  props: {
    userInfo: {
      type: Object
    }
  },
  data() {
    return {
      userMenu: ['查看TA的资料', '查看聊天记录', '加入黑名单', '删除好友'],
      textAreaValue: '',
      customerColor: '',
      messageRecords: [],
      myInfo: {},
    }
  },
  methods: {
    downloadFile(url){
      window.open(url)
    },
    async getHistoryMessage() {
      let res = await getSingleChatHistory(this.userInfo.id, 0, 30);
      res.data.forEach(msg => {
        this.messageRecords.unshift(msg);
        this.$nextTick(() => {
          this.$refs.messageArea.scrollTop = this.$refs.messageArea.scrollHeight;
        });
      });
    },
    handleSendBtnClick() {
      if (this.textAreaValue !== '') {
        let message = {
          roomId: this.userInfo.id,
          message: this.textAreaValue,
          senderId: this.myInfo.id,
          senderName: this.myInfo.username,
          senderNickname: this.myInfo.nickname,
          time: new Date(),
          messageType: "text",
          senderAvatar: this.myInfo.avatar,
          isReadUser: [this.myInfo.id],
          conversationType: "FRIEND"
        };
        this.$socket.emit("sendNewMessage", message)
        this.messageRecords.push(message)
        this.textAreaValue = ""
        this.$nextTick(() => {
          this.$refs.messageArea.scrollTop = this.$refs.messageArea.scrollHeight;
        });
      }
    },
    handleImageSelected(file) {
      let fileForm = new window.FormData();
      fileForm.append('file', file);
      fileForm.append('model', 'chat');
      this.uploadFile(fileForm, 'image');
    },
    handleFileSelected(file) {
      console.log(file);
      let fileForm = new window.FormData();
      fileForm.append('file', file);
      fileForm.append('model', 'chat');
      this.uploadFile(fileForm, 'file');
    },
    async uploadFile(file, type) {
      let token = sessionStorage.getItem("token");
      axios.post(`api/oss/file/upload`, file, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': token
        }
      })
          .then(res => {
            const fileUrl = res.data.data.filePath;
            switch (type) {
              case 'image':
                let message = {
                  roomId: this.userInfo.id,
                  message: fileUrl,
                  senderId: this.myInfo.id,
                  senderName: this.myInfo.username,
                  senderNickname: this.myInfo.nickname,
                  time: new Date(),
                  messageType: "image",
                  senderAvatar: this.myInfo.avatar,
                  isReadUser: [this.myInfo.id],
                  conversationType: "FRIEND"
                };
                this.messageRecords.push(message);
                this.$socket.emit("sendNewMessage", message)
                this.$nextTick(() => {
                  this.$refs.messageArea.scrollTop = this.$refs.messageArea.scrollHeight;
                });
                break;
              case 'file':
                let fileMessage = {
                  roomId: this.userInfo.id,
                  message: fileUrl,
                  senderId: this.myInfo.id,
                  senderName: this.myInfo.username,
                  senderNickname: this.myInfo.nickname,
                  time: new Date(),
                  messageType: "file",
                  senderAvatar: this.myInfo.avatar,
                  isReadUser: [this.myInfo.id],
                  conversationType: "FRIEND"
                };
                this.messageRecords.push(fileMessage);
                this.$socket.emit("sendNewMessage", fileMessage)
                this.$nextTick(() => {
                  this.$refs.messageArea.scrollTop = this.$refs.messageArea.scrollHeight;
                });
            }
          })
          .catch(error => {
            console.log(error);
          });
    },
    updateColor() {
      this.customerColor = document.getElementsByTagName('body')[0].style.getPropertyValue('--custom-color');
    }
  },
  computed: {
    // 计算时间差
    computeDatetime(oldTime, newTime) {
      return (oldTime, newTime) => {
        return (new Date(newTime) - new Date(oldTime)) / 1000 / 60 >= 5; //返回两个时间差是否大于5分钟
      }
    }
  },
  filters: {
    /**
     * 格式化时间
     * @param {String} time 时间字符串
     * @return {String} 格式化后的时间
     */
    formatTime(time) {
      let messageDate = new Date(time);
      let nowDate = new Date();
      let messageTime = {
        year: messageDate.getFullYear(),
        month: messageDate.getMonth() + 1,
        day: messageDate.getDate(),
        hour: messageDate.getHours().toString().padStart(2, '0'),
        min: messageDate.getMinutes().toString().padStart(2, '0'),
        second: messageDate.getSeconds()
      }
      let nowTime = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      if (messageTime.year === nowTime.year && messageTime.month === nowTime.month && messageTime.day === nowTime.day) {
        return `${messageTime.hour}:${messageTime.min}`;
      } else {
        return `${messageTime.year}-${messageTime.month}-${messageTime.day} ${messageTime.hour}:${messageTime.min}`;
      }
    }
  },
  mounted() {
    this.getHistoryMessage();
    this.myInfo = JSON.parse(sessionStorage.getItem("userInfo"));

  },
  created() {
    this.customerColor = sessionStorage.getItem('custom-color') ?? '#4746a3';
  },
  sockets: {
    receiveMessage(message) {
      this.messageRecords.push(message)

      this.$forceUpdate();
      this.$nextTick(() => {
        this.$refs.messageArea.scrollTop = this.$refs.messageArea.scrollHeight;
      });
    }
  },
}
</script>

<style lang="scss" scoped>
@import 'chatFrame.scss';
</style>